package com.kmproject.haifu.mvp.presenter;

import android.app.Activity;
import android.app.Application;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.widget.CustomPopupWindow;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.app.utils.RxUtils;
import com.kmproject.haifu.app.utils.StringUtils;
import com.kmproject.haifu.mvp.contract.HousePublishOfficePublishContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.ResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.HousePublishResultBean;
import com.kmproject.haifu.mvp.model.entity.beans.HouseRentListShowInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.MemberCenterUserInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.MyStoryBean;
import com.kmproject.haifu.mvp.ui.adapter.FloorTypeAndFloorsAdapter;
import com.kmproject.haifu.mvp.ui.adapter.PublicHouseXZDPItemAdapter;
import com.library.flowlayout.SpaceItemDecoration;
import com.suke.widget.SwitchButton;
import com.weigan.loopview.LoopView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 08/07/2019 15:28
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class HousePublishOfficePublishPresenter extends BasePresenter<HousePublishOfficePublishContract.Model, HousePublishOfficePublishContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    int   mselectIndex=0;

    private CustomPopupWindow customPopupWindowSelectStore;//选择归属店铺的view
    private PopuwindowSelectStoreViewHold popuwindowSelectStoreViewHold;
    List<HousePayWayBean> floorTypeAndFloors;

    @Inject
    public HousePublishOfficePublishPresenter(HousePublishOfficePublishContract.Model model, HousePublishOfficePublishContract.View rootView) {
        super(model, rootView);
    }
    /**
     * 更新信息
     * @param mpas
     */
    public void updateHouseRent(Map<String,Object> mpas)
    {
        mModel.updateHouseRent(mpas).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean resultBean) {
                        if (AppUtil.isSuccess(resultBean))
                        {
                            mRootView.updateHouseRentSuccess();
                        }else {
                            mRootView.showMessage(resultBean.getMessage());
                        }
                    }
                });
    }
    /**
     * 获取详情根据id
     * @param houseId
     */
    public void viewHouseRent(String houseId)
    {
        mModel.viewHouseRent(Api.APP_DOMAIN+"/app/viewHouseRent/"+houseId).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<HouseRentListShowInfoBean>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<HouseRentListShowInfoBean> houseRentListShowInfoBeanResultBean) {
                        if (AppUtil.isSuccess(houseRentListShowInfoBeanResultBean))
                        {
                            mRootView.viewHouseRentSuccess(houseRentListShowInfoBeanResultBean.getData());
                        }else {
                            mRootView.showMessage(houseRentListShowInfoBeanResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 发布
     * @param params
     */
    public void  addHouseRent(Map<String, Object> params) {
        mModel.addHouseRent(params).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean resultBean) {
                        if (AppUtil.isSuccess(resultBean))
                        {

                            mRootView.addHouseRentSuccess();
                        }else {
                            mRootView.showMessage(resultBean.getMessage());
                        }
                    }
                });
    }
    /**
     * 获取关联楼层
     */
    public void getFloorTypeAndFloor(List<HousePayWayBean> mfloorTypeAndFloors) {
        if (mfloorTypeAndFloors != null && !mfloorTypeAndFloors.isEmpty()) {
            mRootView.getFloorTypeAndFloor(mfloorTypeAndFloors);
            return;
        }
        mModel.getFloorTypeAndFloor().compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<HousePayWayBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<HousePayWayBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean)) {
                            floorTypeAndFloors = listResultBean.getData();
                            mRootView.getFloorTypeAndFloor(listResultBean.getData());
                        } else {
                            mRootView.showMessage(listResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 选择租金
     *
     * @param activity
     * @param mParentView
     */
    public void selectZj(Activity activity, View mParentView) {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder().parentView(mParentView).contentView(CustomPopupWindow.inflateView(activity, R.layout.house_publish_office_publish_zj)).backgroundDrawable(activity.getResources().getDrawable(R.drawable.button_white_bg))
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isWrap(true).isHaveBackGround(true).isShowBottom(true).build();
        View view1 = customPopupWindow.getContentView();
        TextView housePublishOfficePublishZjSure = view1.findViewById(R.id.house_publish_office_publish_zj_sure);
        EditText housepublishpublishContenYzjTxt = view1.findViewById(R.id.housepublishpublish_conten_yzj_txt);
        SwitchButton switchButtonSfdbgjj = view1.findViewById(R.id.switch_button_sfdbgjj);
        EditText housepublishpublishContenRzjTxt = view1.findViewById(R.id.housepublishpublish_conten_rzj_txt);
        LinearLayout housePublishOfficePublishRzjLay = view1.findViewById(R.id.house_publish_office_publish_rzj_lay);
        if (switchButtonSfdbgjj.isChecked()) {
            housePublishOfficePublishRzjLay.setVisibility(View.VISIBLE);
        } else {
            housePublishOfficePublishRzjLay.setVisibility(View.GONE);
        }
        switchButtonSfdbgjj.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    housePublishOfficePublishRzjLay.setVisibility(View.VISIBLE);
                } else {
                    housePublishOfficePublishRzjLay.setVisibility(View.GONE);
                }
            }
        });
        housePublishOfficePublishZjSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.ViewisEnpty(housepublishpublishContenYzjTxt)) {
                    mRootView.showMessage("请输入月租金");
                    return;
                }
                if (switchButtonSfdbgjj.isChecked()) {
                    if (StringUtils.ViewisEnpty(housepublishpublishContenRzjTxt)) {
                        mRootView.showMessage("请输入日租金");
                        return;
                    }
                    mRootView.getHousePublicBean().setDailyRent(housepublishpublishContenRzjTxt.getText().toString().trim());
                    mRootView.zjTextview().setText(housepublishpublishContenYzjTxt.getText().toString().trim()+"P/月或"+housepublishpublishContenRzjTxt.getText().toString().trim()+"P/天");

                }else {
                    mRootView.zjTextview().setText(housepublishpublishContenYzjTxt.getText().toString().trim()+"P/月");
                }
                mRootView.getHousePublicBean().setMonthRent(Double.parseDouble(housepublishpublishContenYzjTxt.getText().toString().trim()));

                customPopupWindow.dismiss();

            }
        });
        customPopupWindow.show();
    }

    /**
     * 选择楼层
     *
     * @param activity
     * @param mParentView
     */
    public void selectHouseFloor(Activity activity, View mParentView,SelectLcCallback selectLcCallback) {
        mselectIndex=0;
        if (floorTypeAndFloors == null) {
            return;
        }
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder().parentView(mParentView).contentView(CustomPopupWindow.inflateView(activity, R.layout.house_publish_office_publish_xzlc)).backgroundDrawable(activity.getResources().getDrawable(R.drawable.button_white_bg))
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isWrap(true).isHaveBackGround(true).isShowBottom(true).build();
        View view1 = customPopupWindow.getContentView();

        RecyclerView housePublishOfficePublishXzlcRecyclerView=view1.findViewById(R.id.house_publish_office_publish_xzlc_RecyclerView);
        LoopView typeLoopview1=view1.findViewById(R.id.type_loopview1);
        typeLoopview1.setNotLoop();
        typeLoopview1.setTextSize(18);
        typeLoopview1.setCenterTextColor(ArmsUtils.getColor(activity,R.color.color_191919));
        typeLoopview1.setOuterTextColor(ArmsUtils.getColor(activity,R.color.color_C6C6C6));
        typeLoopview1.setCurrentPosition(0);
        typeLoopview1.setDividerColor(ArmsUtils.getColor(activity,R.color.line_greyf5));
        LoopView typeLoopview2=view1.findViewById(R.id.type_loopview2);
        typeLoopview2.setNotLoop();
        typeLoopview2.setTextSize(18);
        typeLoopview2.setCenterTextColor(ArmsUtils.getColor(activity,R.color.color_191919));
        typeLoopview2.setOuterTextColor(ArmsUtils.getColor(activity,R.color.color_C6C6C6));
        typeLoopview2.setCurrentPosition(0);
        typeLoopview2.setDividerColor(ArmsUtils.getColor(activity,R.color.line_greyf5));
        LoopView typeLoopview3=view1.findViewById(R.id.type_loopview3);
        typeLoopview3.setNotLoop();
        typeLoopview3.setTextSize(18);
        typeLoopview3.setCenterTextColor(ArmsUtils.getColor(activity,R.color.color_191919));
        typeLoopview3.setOuterTextColor(ArmsUtils.getColor(activity,R.color.color_C6C6C6));
        typeLoopview3.setCurrentPosition(0);
        typeLoopview3.setDividerColor(ArmsUtils.getColor(activity,R.color.line_greyf5));
        TextView house_publish_office_publish_xzlc_z=view1.findViewById(R.id.house_publish_office_publish_xzlc_z);
        TextView housePublishOfficePublishXzlcSure=view1.findViewById(R.id.house_publish_office_publish_xzlc_sure);
        FloorTypeAndFloorsAdapter floorTypeAndFloorsAdapter=new FloorTypeAndFloorsAdapter(floorTypeAndFloors, new FloorTypeAndFloorsAdapter.ItemClickCallback() {
            @Override
            public void callback(int selectIndex, HousePayWayBean housePayWayBean) {
                mselectIndex=selectIndex;
                if (selectIndex==0)
              {
                  //单层
                  house_publish_office_publish_xzlc_z.setVisibility(View.GONE);
                  typeLoopview1.setVisibility(View.VISIBLE);
                  typeLoopview2.setVisibility(View.GONE);
                  typeLoopview3.setVisibility(View.VISIBLE);
                  typeLoopview1.setItems(getHousePayWay(housePayWayBean.getSubset().getFloor()));
                  typeLoopview3.setItems(getHousePayWay(housePayWayBean.getSubset().getTotalFloor()));

              }else if (selectIndex==1)
              {
                 //多层
                  house_publish_office_publish_xzlc_z.setVisibility(View.VISIBLE);
                  typeLoopview1.setVisibility(View.VISIBLE);
                  typeLoopview2.setVisibility(View.VISIBLE);
                  typeLoopview3.setVisibility(View.VISIBLE);
                  typeLoopview1.setItems(getHousePayWay(housePayWayBean.getSubset().getFloor()));
                  typeLoopview2.setItems(getHousePayWay(housePayWayBean.getSubset().getToFloor()));
                  typeLoopview3.setItems(getHousePayWay(housePayWayBean.getSubset().getTotalFloor()));

              }else {
                  //独栋
                  house_publish_office_publish_xzlc_z.setVisibility(View.GONE);
                  typeLoopview1.setVisibility(View.GONE);
                  typeLoopview2.setVisibility(View.GONE);
                  typeLoopview3.setVisibility(View.VISIBLE);
                  typeLoopview3.setItems(getHousePayWay(housePayWayBean.getSubset().getTotalFloor()));
                }
            }
        });
        housePublishOfficePublishXzlcRecyclerView.setAdapter(floorTypeAndFloorsAdapter);
        LinearLayoutManager layoutManager=new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        housePublishOfficePublishXzlcRecyclerView.setLayoutManager(layoutManager);
        housePublishOfficePublishXzlcRecyclerView.addItemDecoration(new SpaceItemDecoration(AppUtil.dp2px(5)));
        housePublishOfficePublishXzlcSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 if (mselectIndex==0)
                 {
                     selectLcCallback.callback(floorTypeAndFloors.get(mselectIndex).getSubset().getFloor().get(typeLoopview1.getSelectedItem()),null,floorTypeAndFloors.get(mselectIndex).getSubset().getTotalFloor().get(typeLoopview3.getSelectedItem()));
                 }else if (mselectIndex==1)
                 {
                     selectLcCallback.callback(floorTypeAndFloors.get(mselectIndex).getSubset().getFloor().get(typeLoopview1.getSelectedItem()),floorTypeAndFloors.get(mselectIndex).getSubset().getToFloor().get(typeLoopview2.getSelectedItem()),floorTypeAndFloors.get(mselectIndex).getSubset().getTotalFloor().get(typeLoopview3.getSelectedItem()));

                 }else {
                     selectLcCallback.callback(null,null,floorTypeAndFloors.get(mselectIndex).getSubset().getTotalFloor().get(typeLoopview3.getSelectedItem()));

                 }
                customPopupWindow.dismiss();
            }
        });
        customPopupWindow.show();
    }

    /**
     * 获取店铺列表
     */
    public void querySelectStory() {
        Map<String,Object> maps=new HashMap<>();
        maps.put("page",1);
        maps.put("limit", AppConstant.pageSize_big);
        mModel.querySelectStory(maps).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<MyStoryBean.ResultBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<MyStoryBean.ResultBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean)) {
                            mRootView.querySelectStorySuccess(listResultBean.getData());
                        } else {
                            mRootView.showMessage(listResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 得到名字 字符串
     *
     * @param housePayWayBeans
     * @return
     */
    public List<String> getHousePayWay(List<HousePayWayBean> housePayWayBeans) {
        List<String> temName = new ArrayList<>();
        if (housePayWayBeans == null || housePayWayBeans.isEmpty()) {
            return temName;
        }
        for (HousePayWayBean housePayWayBean : housePayWayBeans) {
            temName.add(housePayWayBean.getName());
        }
        return temName;
    }

    /**
     * 获取区域信息
     *
     * @param value
     * @param housePayWayBeans
     */
    public void getAreaTree(String value, List<HousePayWayBean> housePayWayBeans) {
        if (housePayWayBeans != null && !housePayWayBeans.isEmpty()) {
            mRootView.getHouseArea(housePayWayBeans);
            return;
        }
        mModel.getAreaTree(Api.APP_DOMAIN_ZIDIAN + "/app/baseArea/getAreaTree", value, "").compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<HousePayWayBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<HousePayWayBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean)) {
                            mRootView.getHouseArea(listResultBean.getData());
                        } else {
                            mRootView.showMessage(listResultBean.getMessage());
                        }
                    }
                });
    }

    /**
     * 获取付款方式
     *
     * @param value
     * @param category
     */
    public void getHousePayWayBean(String value, String category, List<HousePayWayBean> housePayWayBeans) {
        if (housePayWayBeans != null && !housePayWayBeans.isEmpty()) {
            mRootView.getHousePayWayBeanSuccess(housePayWayBeans);
            return;
        }//dictList4Category

        mModel.getHousePayWayBean(value, category).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<ResultBean<List<HousePayWayBean>>>(mErrorHandler) {
                    @Override
                    public void onNext(ResultBean<List<HousePayWayBean>> listResultBean) {
                        if (AppUtil.isSuccess(listResultBean)) {
                            mRootView.getHousePayWayBeanSuccess(listResultBean.getData());
                        } else {
                            mRootView.showMessage(listResultBean.getMessage());
                        }

                    }
                });
    }

    /**
     * 选择店铺
     *
     * @param activity
     * @param view
     * @param memberCenterUserInfoBean
     * @param resultBeans
     * @param callback
     */
    public void popuwindSelectStore(Activity activity, View view, MemberCenterUserInfoBean memberCenterUserInfoBean, List<MyStoryBean.ResultBean> resultBeans, HousePublishDuanZuPublishPresenter.SelectStoreCallback callback) {

        customPopupWindowSelectStore = new CustomPopupWindow.Builder().contentView(CustomPopupWindow.inflateView(activity, R.layout.housepublishpublish_selectstory)).parentView(view)
                .animationStyle(R.style.mypopwindow_anim_style).customListener(new CustomPopupWindow.CustomPopupWindowListener() {
                    @Override
                    public void initPopupView(View contentView) {

                    }
                }).isHaveBackGround(false).build();
        View view1 = customPopupWindowSelectStore.getContentView();
        popuwindowSelectStoreViewHold = new PopuwindowSelectStoreViewHold(view1);
        popuwindowSelectStoreViewHold.toolbarTitle.setText(ArmsUtils.getString(activity, R.string.housepublishpublish_title_xzgsdp));
        popuwindowSelectStoreViewHold.toolbarTitle.setTextColor(ArmsUtils.getColor(activity, R.color.color_191919));
        popuwindowSelectStoreViewHold.toolbar.setBackgroundColor(ArmsUtils.getColor(activity, R.color.color_EDEDED));
        popuwindowSelectStoreViewHold.toolbarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customPopupWindowSelectStore.dismiss();
            }
        });
        popuwindowSelectStoreViewHold.housepublishpublishSelectstoryRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
        PublicHouseXZDPItemAdapter adapter = new PublicHouseXZDPItemAdapter(memberCenterUserInfoBean, resultBeans);
        popuwindowSelectStoreViewHold.housepublishpublishSelectstoryRecyclerView.setAdapter(adapter);
        adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                callback.callBack(resultBeans.get(position));
                customPopupWindowSelectStore.dismiss();
            }
        });
        customPopupWindowSelectStore.show();
    }

    public class PopuwindowSelectStoreViewHold {

        @BindView(R.id.toolbar_backImg)
        ImageView toolbarBackImg;
        @BindView(R.id.toolbar_back)
        RelativeLayout toolbarBack;
        @BindView(R.id.toolbar_title)
        TextView toolbarTitle;
        @BindView(R.id.back_right_icon)
        ImageView backRightIcon;
        @BindView(R.id.back_right_txt)
        TextView backRightTxt;
        @BindView(R.id.toolbar_right)
        RelativeLayout toolbarRight;
        @BindView(R.id.toolbar)
        AutoToolbar toolbar;
        @BindView(R.id.housepublishpublish_selectstory_RecyclerView)
        RecyclerView housepublishpublishSelectstoryRecyclerView;

        public PopuwindowSelectStoreViewHold(View view) {
//            R.layout.housepublishpublish_selectstory
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 楼层回调
     */
    public interface SelectLcCallback {
        public void callback(HousePayWayBean floor, HousePayWayBean toFloor, HousePayWayBean totalFloor);
    }

    /**
     * 租金回调
     */
    public interface SelectZjCallback {
        public void callback(String monthRent, String dayRent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }
}
